package com.huluobo.a2204kotlinjetpackdemo.paging

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.huluobo.a2204kotlinjetpackdemo.databinding.ItemFooterBinding

/**
 *  Created by LC on 2024/8/19.
 */
class FooterAdapter(val retry: () -> Unit) : LoadStateAdapter<FooterAdapter.ViewHolder>() {
    class ViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onBindViewHolder(holder: ViewHolder, loadState: LoadState) {
        val binding = holder.binding as ItemFooterBinding
        when (loadState) {
            is LoadState.NotLoading -> {
                //加载完成,没有其他加载数据进行时
                binding.progressBar.visibility = View.GONE
                binding.retryBtn.visibility = View.GONE
            }

            is LoadState.Loading -> {
                //读取中
                binding.progressBar.visibility = View.VISIBLE
                binding.retryBtn.visibility = View.VISIBLE
                binding.retryBtn.text = "读取中..."
            }

            is LoadState.Error -> {
                binding.progressBar.visibility = View.GONE
                binding.retryBtn.visibility = View.VISIBLE
                binding.retryBtn.text = "加载失败,点击重试"
                binding.retryBtn.setOnClickListener {
                    retry()
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): ViewHolder {
        val binding: ItemFooterBinding = ItemFooterBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }
}